<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="adddrold(1, '0')"
          >添加权限</el-button>
        </div>

        <el-table border :data="PermissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.type === 1"
                type="text"
                @click="adddrold(2, scope.row.id)"
              >添加</el-button>
              <el-button
                type="text"
                @click="edtrold(scope.row.id)"
              >编辑</el-button>
              <el-button
                type="text"
                @click="delrold(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 弹出层 -->
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog
          :title="isedit ? '编辑权限点' : '新增权限点'"
          :visible="showDialog"
          @close="btnCancel"
        >
          <!-- 表单 -->
          <el-form
            ref="perForm"
            :model="formData"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width: 90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button
                size="small"
                type="primary"
                @click="addOredit"
              >确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入树形组件处理函数
import { tranListToTreeData } from '@/utils'
// 引入获取权限点的api
import {
  getPermissionList,
  addPermission,
  getPermissionDetail,
  updatePermission,
  delPermission
} from '@/api/permission'
export default {
  name: 'Permission',
  data() {
    const validName = (rule, value, callback) => {
      // 添加判断重名
      let existNameList = this.originList
        .filter(item => item.pid === this.formData.pid)
        .map(item => item.name)
      // 编辑判断重名
      if (this.isedit) {
        existNameList = this.originList
          .filter(
            item =>
              item.pid === this.formData.pid && item.id !== this.formData.id
          )
          .map(item => item.name)
      }
      existNameList.includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    const validCode = (rule, value, callback) => {
      // 添加判断重复权限标识
      let existCodeList = this.originList
      // 编辑判断重复权限标识
      if (this.isedit) {
        existCodeList = this.originList.filter(
          item => item.id !== this.formData.id
        )
      }
      existCodeList.map(item => item.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      PermissionList: [], // 权限点列表
      showDialog: false,
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isedit: false,
      originList: []
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 添加权限的功能(api)
    async addPermission() {
      const res = await addPermission(this.formData)
      this.$message.success(res.message)
      this.getPermissionList()
      this.showDialog = false
    },
    // 添加权限的功能(api)
    async editPermission() {
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.getPermissionList()
      this.showDialog = false
    },
    // 点击弹出层的确定按钮
    addOredit() {
      this.$refs.perForm.validate(async(valid) => {
        if (!valid) return
        this.isedit ? this.editPermission() : this.addPermission()
      })
    },
    // 点击弹出层的取消按钮
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 标识
        description: '', // 描述
        type: '', // 类型 该类型 不需要显示 因为点击添加的时候已经知道类型了
        pid: '', // 因为做的是树 需要知道添加到哪个节点下了
        enVisible: '0' // 开启
      }
      // 重置弹出层表单的数据
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },
    // 获取权限点列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.PermissionList = tranListToTreeData(res.data, '0')
      this.originList = res.data.map(({ id, pid, name, code }) => ({
        id,
        pid,
        name: name.trim(),
        code
      }))
    },
    // (添加按钮)添加权限
    adddrold(type, pid) {
      this.isedit = false
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
    },

    // (编辑按钮)编辑权限数据回填
    async edtrold(id) {
      this.isedit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
    },
    // (删除按钮)删除权限
    async delrold(id) {
      const dett = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(dett)
      if (dett === 'cancel') return this.$message('您已经取消删除')
      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
